package com.mnb.beidou.controller;

import com.alibaba.fastjson.JSON;
import com.mnb.beidou.model.CusOrimes;
import com.mnb.beidou.service.TcpMessageService;
import com.mnb.beidou.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.mnb.beidou.listener.MqttConnectionListener;
import com.mnb.beidou.service.MessageService;

import java.util.HashMap;
import java.util.Map;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 北斗消息控制器
 * 提供REST API接口
 */
@RestController
@RequestMapping("/beidou")
public class BeidouController {
    
    @Autowired
    private MessageService beidouMessageService;

    @Autowired
    private TcpMessageService tcpMessageService;
    
    @Autowired
    private MqttConnectionListener mqttConnectionListener;
    
    /**
     * 获取MQTT连接状态
     */
    @GetMapping("/mqtt/status")
    public Map<String, Object> getMqttStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("connected", mqttConnectionListener.isConnected());
        status.put("reconnectAttempts", mqttConnectionListener.getReconnectAttempts());
        status.put("timestamp", System.currentTimeMillis());
        return status;
    }
    
    /**
     * 手动重连MQTT
     */
    @PostMapping("/mqtt/reconnect")
    public Map<String, Object> reconnectMqtt() {
        Map<String, Object> result = new HashMap<>();
        try {
            mqttConnectionListener.manualReconnect();
            result.put("success", true);
            result.put("message", "MQTT重连请求已发送");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "MQTT重连失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 处理北斗消息的接口
     */
    @GetMapping("/modbus")
    public R modbus(CusOrimes cusOrimes) {
        beidouMessageService.processMessage(JSON.toJSONString(cusOrimes), "人工补数");
        return R.ok();
    }

    /**
     * 处理tcp消息的接口
     */
    @GetMapping("/psModbus")
    public R psModbus(CusOrimes cusOrimes) {
        tcpMessageService.processMessage(cusOrimes.getContent(), cusOrimes.getTime());
        return R.ok();
    }


    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("mqtt", mqttConnectionListener.isConnected() ? "CONNECTED" : "DISCONNECTED");
        health.put("timestamp", System.currentTimeMillis());
        return health;
    }
    
    /**
     * 网络连接测试接口
     */
    @GetMapping("/network/test")
    public Map<String, Object> testNetworkConnection() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试DNS解析
            String host = "mgtt.bds100.com";
            InetAddress address = InetAddress.getByName(host);
            result.put("dns_resolution", "SUCCESS");
            result.put("ip_address", address.getHostAddress());
            
            // 测试端口连接
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(host, 32324), 5000);
                result.put("port_connection", "SUCCESS");
                result.put("port", 32324);
            } catch (Exception e) {
                result.put("port_connection", "FAILED");
                result.put("port_error", e.getMessage());
            }
            
            result.put("success", true);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 简单MQTT连接测试
     */
    @GetMapping("/mqtt/test")
    public Map<String, Object> testMqttConnection() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查MQTT适配器状态
            boolean isRunning = mqttConnectionListener.isConnected();
            result.put("mqtt_connected", isRunning);
            result.put("reconnect_attempts", mqttConnectionListener.getReconnectAttempts());
            
            // 获取连接信息
            result.put("broker_url", "mgtt.bds100.com:32324");
            result.put("client_id", "mqttx_d8c45057_spring");
            result.put("username", "psbs2");
            result.put("protocol", "tcp://");
            result.put("mqtt_version", "3.1.1");
            
            result.put("success", true);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
} 